package util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;

public class CryptographyUtil {

	public static String hashMD5(String str) {
		String hashedStr = null; // / Result to be returned
		try {
			MessageDigest md = MessageDigest.getInstance("MD5"); // / Select
																	// Algorithm
			md.update(str.getBytes(), 0, str.length()); // / Encrypt
			hashedStr = new BigInteger(1, md.digest()).toString(16); // / Get
																		// result
		} catch (java.security.NoSuchAlgorithmException noAl) {
			return str;
		}

		return hashedStr;
	}

	/**
	 * @param encryptedString
	 * @param secrectKey
	 *            8 chars
	 * @return
	 * @throws InvalidKeyException
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 * @throws UnsupportedEncodingException
	 */
	public static String decryptDES(String encodedStr, String keyStr)
			throws InvalidKeyException, NoSuchAlgorithmException,
			InvalidKeySpecException, UnsupportedEncodingException {
		String descryptedStr = null;
		byte[] keyBytes = keyStr.getBytes();
		DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secKey = keyFactory.generateSecret(desKeySpec);
		try {
			Cipher dCipher = Cipher.getInstance("DES");
			dCipher.init(Cipher.DECRYPT_MODE, secKey);

			byte[] encodedBytes = encodedStr.getBytes();
			byte[] decodedBytes = dCipher.doFinal(encodedBytes);
			descryptedStr = new String(decodedBytes, "UTF8");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}

		return descryptedStr;
	}

}
